package com.qf.servlet;

import com.qf.pojo.PageBean;
import com.qf.pojo.Product;
import com.qf.service.ProductService;
import com.qf.service.impl.ProductServiceImpl;
import com.qf.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 针对商品后台的控制器
 */
@WebServlet("/product")
public class ProductServlet extends BaseServlet {


    /**
     * 根据商品pid获取商品实体
     * @param request 请求对象
     * @param response 响应对象
     */
    public void getProductById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //1)获取商品pid
        String pid = request.getParameter("pid");
       // System.out.println(pid);

        //2)调用商品的业务接口
        ProductService productService = new ProductServiceImpl() ;
        Product product = productService.getProduct(pid);

//        System.out.println(product);
        /*String s = JsonUtils.object2json(product);
        response.getWriter().write(s);*/


        //3)存储到Request域中
        request.setAttribute("product",product);
        //4)请求转发到"/jsp/product_info.jsp"
        request.getRequestDispatcher("/jsp/product_info.jsp").forward(request,response);
    }


    /**
     * 根据分类id获取商品分页信息
     * @param request 请求对象
     * @param response 响应对象
     */
    public void findProductByPage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //href='${pageContext.request.contentType}/product?methodName=findProductByPage&currentPage=1&pageSize=12&cid="+this.cid+"'
        //获取当前页码/每页显示的条数,以及分类id
        String curPage = request.getParameter("currentPage");
        String pSize = request.getParameter("pageSize");
        String cid = request.getParameter("cid");
        //System.out.println(curPage+"---"+pSize+"---"+cid);

        //将curPage,pSize转换成int类型
        int currentPage = Integer.parseInt(curPage);
        int pageSize = Integer.parseInt(pSize);

        //调用商品业务接口
        ProductService productService = new ProductServiceImpl() ;
        PageBean<Product> pb = productService.getProductByPage(currentPage, pageSize, cid);

        System.out.println(pb);
        //将pb对象存储在request域中
        request.setAttribute("pb",pb);
        request.getRequestDispatcher("/jsp/product_list.jsp").forward(request,response);



    }
}
